import customtkinter as ctk
from datetime import datetime


class LogTab(ctk.CTkFrame):
    def __init__(self, parent):
        super().__init__(parent)
        self._init_ui()

    def _init_ui(self):
        self.pack(fill='both', expand=True)
        ctk.CTkLabel(self, text='运行日志').pack(anchor='w', padx=10, pady=(10, 0))
        self.logEdit = ctk.CTkTextbox(self, height=400)
        self.logEdit.configure(state='normal')
        self.logEdit.pack(fill='both', expand=True, padx=10, pady=10)

        btnRow = ctk.CTkFrame(self)
        clearBtn = ctk.CTkButton(btnRow, text='清除日志', command=self.clear)
        exportBtn = ctk.CTkButton(btnRow, text='导出日志', command=self.export)
        clearBtn.pack(side='left', padx=10, pady=10)
        exportBtn.pack(side='left', padx=10, pady=10)
        btnRow.pack(fill='x', padx=10)

    def append(self, message: str):
        ts = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.logEdit.insert('end', f'[{ts}] {message}\n')
        self.logEdit.see('end')

    def clear(self):
        self.logEdit.delete('1.0', 'end')
        self.append('日志已清除')

    def export(self):
        ts = datetime.now().strftime('%Y%m%d_%H%M%S')
        fn = f'logs_{ts}.txt'
        with open(fn, 'w', encoding='utf-8') as f:
            f.write(self.logEdit.get('1.0', 'end'))
        self.append(f'日志已导出到: {fn}')

